package com.lechi.web.util;

import com.lechi.web.common.constant.ScheduleConstants;
import com.lechi.web.common.exception.job.TaskException;
import com.lechi.web.common.utils.StringUtils;
import com.lechi.web.framework.util.CronUtils;
import com.lechi.web.job.DataCheckJobExecution;
import com.lechi.web.job.SendCmdJobExecution;
import com.lechi.web.system.domain.IotScheduleJobBo;
import org.quartz.*;

/**
 * 定时任务工具类
 *
 * @author yg
 */
public class ScheduleUtils {

    /**
     * 构建任务触发对象
     */
    public static TriggerKey getTriggerKey(Long jobId, String jobGroup) {
        return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 构建任务键对象
     */
    public static JobKey getJobKey(Long jobId, String jobGroup) {
        return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, IotScheduleJobBo job, String jobGroup) throws SchedulerException, TaskException {
        Class<? extends Job> jobClass = "run".equals(job.getJobType()) ? SendCmdJobExecution.class : DataCheckJobExecution.class;
        // 构建job信息
        Long jobId = job.getId();
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build();

        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup))
                .withSchedule(cronScheduleBuilder).build();

        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);
        if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
            scheduler.deleteJob(getJobKey(jobId, jobGroup));
        }

        if (StringUtils.isNotNull(CronUtils.getNextExecution(job.getCronExpression()))) {
            scheduler.scheduleJob(jobDetail, trigger);
        }
    }
}
